package pro5_decoder_encoder.ex3_codec;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import pro5_decoder_encoder.ex2_encoder.MyServerHandler;


/**
 * @program: netty
 * @description:
 * @author: zy
 * @create: 2025-03-23 08:52
 */
public class MyServer {
    private int port;

    public MyServer(int port) {
        this.port = port;
    }

    private static final int MASTER_REACTOR_SIZE = 1;

    private static final int SLAVE_REACTOR_SIZE = Runtime.getRuntime().availableProcessors();

    private static final int BUSINESS_THREAD_SIZE = Runtime.getRuntime().availableProcessors() * 2;

    public void run() throws Exception {
        EventLoopGroup masterReactorGroup = new NioEventLoopGroup(MASTER_REACTOR_SIZE);
        //从reactor线程组(处理IO请求)
        EventLoopGroup slaveReactorGroup = new NioEventLoopGroup(SLAVE_REACTOR_SIZE);
        // 业务线程组(处理业务逻辑)
        EventLoopGroup businessGroup = new NioEventLoopGroup(BUSINESS_THREAD_SIZE);
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(masterReactorGroup, slaveReactorGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                           // ch.pipeline().addLast("decoder", new MyDecoder());
                          //  ch.pipeline().addLast("encoder", new MyEncoder());

                            ch.pipeline().addLast(new MyCodec());   //使用组合的编解码器
                            ch.pipeline().addLast(businessGroup,new MyServerHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();

            System.out.println("Server start listen at " + port);

            f.channel().closeFuture().sync();

        } finally {
            masterReactorGroup.shutdownGracefully();
            slaveReactorGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8082;
        }
        new MyServer(port).run();
    }
}
